package io.github.biezhi.elves.bidding.model;

import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;
import io.github.biezhi.elves.utils.DateUtils;
import io.github.biezhi.elves.utils.StringUtils;
import io.github.biezhi.elves.common.BiddingNoticeOperationMode;
import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.common.MapConstants;
import io.github.biezhi.elves.utils.AbstractObject;

/**
 * 公告清单DO对象
 * @author asus-pc
 *
 */
@Data
public class BiddingListDTO extends AbstractObject {
	//表名
	private String tableName = "t_bidding_list_yqx";
	//id
	private Long id;
	//公告记录id
	private String recordId;
	//公告标题
	private String noticeTitle;
	//项目ID
	private String prjId;
	//项目名称
	private String prjName;
	//公告方式
	private String noticeName;
	//采购方式
	private String buyType = "公开招标";
	//客户（发标、采购方）
	private String customer;
	//供应商
	private String supplier;
	//预算金额（元）
	private String budget;
	//成交额（元）
	private String bidPrice;
	//发标时间
	private String publishTime;
	//中标时间
	private String dealTime;
	//行业
	private String industry = "";
	//url
	private String bidUrl;
	//城市
	private String city;
	//是否专项
	private Integer special = -1;
	//专项名称
	private String specialName = "";
	//发布日期
	private String pubdate;
	//项目类型
	private Integer prjType;
	//战略客户
	private String strategicCustomer;
	//公告详情html数据
	private String noticeHtml;
	//公告详情iframeHtml数据
	private String noticeIframeHtml;
	//是否人工干预(0：否；1：是)
	private Integer manual = 1;
	//匹配上的关键字
	private String matchKeyword = "";
	//创建时间
	private Date createTime = DateUtils.stringToDate(DateUtils.getCurrentDay(), DateUtils.dateformat8);
	//网站名称
	private String siteName;
	//多个供应商
	private String[] suppliers;
	//多个成交额（元）
	private String[] bidPrices;
	
	public BiddingListDTO() {}
	public BiddingListDTO(BiddingListDTO bidding, RecordBiddingNoticeDTO recordNotice) {
		this.prjId = StringUtils.isNullOrEmpty(bidding.getPrjId()) ? "-1" : bidding.getPrjId();
		this.noticeTitle = recordNotice.getTitle();
		this.prjName = StringUtils.isNullOrEmpty(bidding.getPrjName()) ? "-1" : bidding.getPrjName();
		this.noticeName = StringUtils.isNullOrEmpty(bidding.getNoticeName()) ? "-1" : bidding.getNoticeName();
		this.buyType = bidding.getBuyType();
		this.customer = StringUtils.isNullOrEmpty(bidding.getCustomer()) ? "-1" : bidding.getCustomer();
		this.supplier = StringUtils.isNullOrEmpty(bidding.getSupplier()) ? "-1" : bidding.getSupplier();
		this.budget = "0.0";
		try {
			if (!StringUtils.isNullOrEmpty(bidding.getBudget())) {
				Double.valueOf(bidding.getBudget());
				this.budget = bidding.getBudget();
			} else {
				this.budget = "0.0";
			}
		} catch (Exception e) {}
		
		this.bidPrice = "0.0";
		try {
			if (!StringUtils.isNullOrEmpty(bidding.getBidPrice())) {
				Double.valueOf(bidding.getBidPrice());
				this.bidPrice = bidding.getBidPrice();
			} else {
				this.bidPrice = "0.0";
			}
		} catch (Exception e) {}
		
		this.publishTime = bidding.getPublishTime();
		this.dealTime = bidding.getDealTime();
		this.bidUrl = recordNotice.getNoticeDetailUrl();
		this.city =  matchCityByName(bidding.getCity(), bidding);
		this.pubdate = DateUtils.dateToStringFormat(recordNotice.getPubdate(), DateUtils.dateformat8, DateUtils.dateformat8);
		this.manual = checkManual(bidding);
		this.noticeHtml = bidding.getNoticeHtml();
		this.siteName = getSiteNameToEnByUrl(bidding.getBidUrl());
	}
	
	public String getCity() {
		String customer = this.customer;
		String noticeTitle = this.noticeTitle;
		if (StringUtils.isNullOrEmpty(customer) || "-1".equals(customer)) {
			System.out.println("customer==>" + customer);
		}
		if ((!StringUtils.isNullOrEmpty(customer) && !"-1".equals(customer))
				|| (!StringUtils.isNullOrEmpty(noticeTitle) && !"-1".equals(noticeTitle))) {
			BiddingListDTO bidding = new BiddingListDTO();
			bidding.setCustomer(this.customer);
			bidding.setNoticeTitle(this.noticeTitle);
			return matchCityByName(this.city, bidding);
		}
		return "";
	}
	
	public String getSiteName() {
		return getSiteNameToEnByUrl(this.bidUrl);
	}
	
	/**
	 * 根据url获取网站名称
	 * @param url
	 * @return
	 */
	private String getSiteNameToEnByUrl(String url) {
		String resultSiteName = "";
		if (!StringUtils.isNullOrEmpty(url)) {
			String result = url.replace("http://", "").replace("https://", "");
			result = result.substring(0, result.indexOf("/"));
			resultSiteName = StringUtils.getValueForKey(result, MapConstants.SITE_BY_EN_MAP);
		}
		return resultSiteName;
	}
	
	/**
	 * 判断地市是否为-1，如果为-1，根据公告标题获取地市，依然为-1，设置为广东省
	 * @param name		参数说明：公告标题或客户（发标、采购方）
	 * @return
	 */
	public String matchCityByName(String paramCity, BiddingListDTO bidding) {
		String city = paramCity;
		String name = getName(bidding);
		if (!StringUtils.isNullOrEmpty(name) && !"-1".equals(name)) {
			if ("-1".equals(paramCity) || StringUtils.isNullOrEmpty(paramCity)) {
				String[] cityNames = Constants.CITY_NAMES;
				for (String cityName : cityNames) {
					if (name.contains(cityName)) {
						city = cityName;
						break;
					}
				}
				if ("-1".equals(city) || StringUtils.isNullOrEmpty(city)) {
					city = "广东省";
				}
			}
			city = city.replace("省", "");
			return city;
		}
		return "";
	}
	
	/**
	 * 获取发标人或公共标题
	 * @param bidding
	 * @return
	 */
	private String getName(BiddingListDTO bidding) {
		String customer = bidding.getCustomer();
		String noticeTitle = bidding.getNoticeTitle();
		String name = customer;
		if ((StringUtils.isNullOrEmpty(name) || "-1".equals(name))
				&& (!StringUtils.isNullOrEmpty(noticeTitle) || "-1".equals(noticeTitle))) {
			name = noticeTitle;
		}
		return name;
	}
	
	public String getBuyType() {
		return this.buyType.replace("；", "");
	}
	
	public void setBudget(String budgetResult) {
		this.budget = dealNumber(budgetResult);
	}
	
	public void setBidPrice(String bidPriceResult) {
		this.bidPrice = dealNumber(bidPriceResult);
	}
	
	public String[] getBidPrices() {
		if (this.bidPrices != null) {
			StringBuffer bidPricesBuffer = new StringBuffer(this.bidPrices.length);
			for (int i = 0; i < bidPrices.length; i++) {
				String bidPriceResult = dealNumber(bidPrices[i]);
				bidPricesBuffer.append(bidPriceResult);
				if (i != (bidPrices.length -1)) {
					bidPricesBuffer.append(",");
				}
			}
			if (!StringUtils.isNullOrEmpty(bidPricesBuffer.toString())) {
				String bidPricesString = bidPricesBuffer.toString();
				String[] bidPricesResult = bidPricesString.split(",");
				this.bidPrices = bidPricesResult;
			}
		}
		return this.bidPrices;
	}
	
	/**
	 * 处理数字或小数点
	 * @param priceResult
	 * @return
	 */
	private String dealNumber(String priceResult) {
		if (StringUtils.isNullOrEmpty(priceResult)) {
			return null;
		}
		priceResult = priceResult.replace("元", "").replace("¥", "").replace("￥", "").replace(" ", "")
				.replace(",", "").replace("人民币", "").replace("/公里", "").replace(" /公里", "")
				.replace("（", "").replace("）", "");
		
		String priceString = "";
		if (priceResult.contains("万")) {
			priceString = priceResult.substring(priceResult.length() - 1);
		}
//		String priceCheck = StringUtils.regexData(priceResult, "([1-9]\\d*\\,?\\d*,\\,?\\d*)|(0\\,\\d*[1-9],\\d*[0-9])");
		String priceCheck = StringUtils.regexData(priceResult, "([1-9]\\d*(\\.\\d*[0-9])?)|(0\\.\\d*[0-9])");
		if (StringUtils.isNullOrEmpty(priceCheck)) {
			priceCheck = StringUtils.regexData(priceResult, "^[0-9]*[1-9][0-9]*$");
			if (StringUtils.isNullOrEmpty(priceCheck)) {
				priceCheck = StringUtils.regexData(priceResult, "[0-9]*[1-9][0-9]*$");
			}
			if (StringUtils.isNullOrEmpty(priceCheck)) {
				priceCheck = StringUtils.regexData(priceResult, "([1-9]\\d*(\\.\\d*[0-9])?)|(0\\.\\d*[0-9])");
			}
			if (StringUtils.isNullOrEmpty(priceCheck)) {
				priceCheck = StringUtils.regexData(priceResult, "\\+{0,1}[0]\\.[1-9]*|\\+{0,1}[1-9]\\d*\\.\\d*");
			}
		}
		if (priceResult.contains("万元") || "万".equals(priceString)) {
			String priceReplace = priceCheck.replace(",", "").replace("万", "");
			if (priceReplace.lastIndexOf(".") != -1) {
				String[] bidPrices = priceReplace.split("\\.");
				priceResult = conventNumber(bidPrices[0], priceReplace);
			} else {
				if (!StringUtils.isNullOrEmpty(priceReplace) && priceReplace.length() < 6) {
					priceResult = conventNumber("", priceReplace);
				}
			}
		} else {
			if (priceResult.contains("%")) {
				priceResult = "0.0";
			} else {
				priceResult = priceCheck.replace("万", "");
				priceResult = StringUtils.isNullOrEmpty(priceResult) ? "0.0" : priceResult;
			}
		}
		priceResult = priceResult.replace(" ", "").replace(",", "");
		return priceResult;
	}
	
	/**
	 * 处理万字，补0处理
	 * @param number
	 * @param price
	 * @return
	 */
	private String conventNumber(String number, String price) {
		String numberResult = number;
		try {
			if (!StringUtils.isNullOrEmpty(number) && number.length() < 6) {
//				Double numberDouble = Double.valueOf(price);
//				numberDouble = numberDouble * 10000;
				int mdVal = 10000;
				BigDecimal md = new BigDecimal(mdVal);
				BigDecimal mb = new BigDecimal(price);
				BigDecimal mul = mb.multiply(md);
				numberResult = String.valueOf(mul);
			}
		} catch (Exception e) {
			System.out.println(number + "," + price);
			e.printStackTrace();
//			System.exit(0);
			numberResult = "0.0";
		}
		return numberResult;
	}
	
	public String getPublishTime() {
		String publishTime = this.publishTime;
		if (StringUtils.isNullOrEmpty(publishTime) && !StringUtils.isNullOrEmpty(publishTime)) {
			String publishTimeString = publishTime.replace("年", "-").replace("月", "-").replace("日", "")
					.replace("/", "-");
			publishTimeString = DateUtils.dateToStringFormat(publishTimeString, DateUtils.dateformat8, DateUtils.dateformat14);
			publishTime = publishTimeString;
		}
		return publishTime;
	}
	
	public String getDealTime() {
		String dealTime = this.dealTime;
		String pubdate = this.pubdate;
		if (StringUtils.isNullOrEmpty(dealTime) && !StringUtils.isNullOrEmpty(pubdate)) {
			dealTime = pubdate;
			String dealTimeString = dealTime.replace("年", "-").replace("月", "-").replace("日", "")
					.replace("/", "-");
			dealTimeString = DateUtils.dateToStringFormat(dealTimeString, DateUtils.dateformat8, DateUtils.dateformat14);
			dealTime = dealTimeString;
		}
		return dealTime;
	}
	
	public String getPubdate() {
		String pubdate = this.pubdate;
		if (!StringUtils.isNullOrEmpty(pubdate)) {
			String pubdateString = pubdate.replace("年", "-").replace("月", "-").replace("日", "")
					.replace("/", "-");
			pubdateString = DateUtils.dateToStringFormat(pubdateString, DateUtils.dateformat8);
			pubdate = pubdateString;
		}
		return pubdate;
	}
	
	/**
	 * 验证公告数据是否需要人工干预
	 */
	public Integer checkManual(BiddingListDTO biddingList) {
		if (!StringUtils.isNullOrEmpty(biddingList.getNoticeTitle())
			&& !"-1".equals(biddingList.getNoticeTitle())
			&& !StringUtils.isNullOrEmpty(biddingList.getPrjId())
			&& !"-1".equals(biddingList.getPrjId())
			&& !StringUtils.isNullOrEmpty(biddingList.getPrjName())
			&& !"-1".equals(biddingList.getPrjName())
			&& !StringUtils.isNullOrEmpty(biddingList.getNoticeName())
			&& !"-1".equals(biddingList.getNoticeName())
			&& !StringUtils.isNullOrEmpty(biddingList.getBuyType())
			&& !"-1".equals(biddingList.getBuyType())
			&& !StringUtils.isNullOrEmpty(biddingList.getCustomer())
			&& !"-1".equals(biddingList.getCustomer())
			&& !StringUtils.isNullOrEmpty(biddingList.getSupplier())
			&& !"-1".equals(biddingList.getSupplier())
			&& !StringUtils.isNullOrEmpty(biddingList.getBudget())
			&& !"0.0".equals(biddingList.getBudget())
			&& !StringUtils.isNullOrEmpty(biddingList.getBidPrice())
			&& !"0.0".equals(biddingList.getBidPrice())
			&& !StringUtils.isNullOrEmpty(biddingList.getDealTime())
			&& !"-1".equals(biddingList.getDealTime())
			&& !StringUtils.isNullOrEmpty(biddingList.getCity())
			&& !"-1".equals(biddingList.getCity())) {
			return BiddingNoticeOperationMode.NON_MANUAL;
		}
		return BiddingNoticeOperationMode.MANUAL;
	}
	
	public static void main(String[] args) {
		String url = "http://www.bidcenter.com.cn/zbpage-4-%E5%B9%BF%E4%B8%9C-1.html";
		String result = url.replace("http://", "").replace("https://", "");
		result = result.substring(0, result.indexOf("/"));
		System.out.println(StringUtils.getValueForKey(result, MapConstants.SITE_BY_EN_MAP));
	}
}